package com.xiliubit.cloudpicture.manager;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.xiliubit.cloudpicture.config.CosClientConfig;
import com.xiliubit.cloudpicture.exception.BusinessException;
import com.xiliubit.cloudpicture.exception.ErrorCode;
import com.xiliubit.cloudpicture.exception.ThrowUtils;
import com.xiliubit.cloudpicture.model.dto.file.PictureUploadResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

//@Service
/**
 * 文件服务
 * @deprecated 已废弃，改为使用 upload 包的模板方法优化
 */
@Deprecated

@Slf4j
public class FileManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 上传图片
     *
     * @param multipartFile 图片
     * @param uploadPathPrefix 上传路径前缀
     */
    public PictureUploadResult putPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        // 校验图片
        validPicture(multipartFile);
        // 图片地址
        String originalFilename = multipartFile.getOriginalFilename();
        String Suffix = FileUtil.getSuffix(originalFilename);
        String uploadFilename = String.format("%s_%s.%s", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                RandomUtil.randomString(8), Suffix);
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);


        // 文件目录
        String filepath = String.format("/test/%s", originalFilename);
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(file, uploadPath);
            // 获取图片信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            int PictureHeight = imageInfo.getHeight();
            int PictureWidth = imageInfo.getWidth();

            // 封装信息
            PictureUploadResult pictureUploadResult = new PictureUploadResult();
            pictureUploadResult.setName(FileUtil.mainName(originalFilename));
            pictureUploadResult.setUrl(cosClientConfig.getHost() + uploadPath);
            pictureUploadResult.setPicFormat(imageInfo.getFormat());
            pictureUploadResult.setPicSize(multipartFile.getSize());
            pictureUploadResult.setPicHeight(PictureHeight);
            pictureUploadResult.setPicWidth(PictureWidth);
            // 这里将整数转化为double，避免精度丢失
            pictureUploadResult.setPicScale(PictureHeight * 1.0 / PictureWidth);
            return pictureUploadResult;
        } catch (Exception e) {
            log.error("文件上传失败: {}", filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            deleteTempFile(file, filepath);
        }

    }

    private static void deleteTempFile(File file, String filepath) {
        if (file != null) {
            // 删除临时文件
            boolean delete = file.delete();
            if (!delete) {
                log.error("临时文件删除失败： {}", filepath);
            }
        }
    }

    /**
     * 校验图片
     *
     * @param multipartFile 图片
     */
    public void validPicture(MultipartFile multipartFile) {
        // 不能为空
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR);
        // 大小不能超过3mb
        final long ONE_M = 1024 * 1024L;
        ThrowUtils.throwIf(multipartFile.getSize() > ONE_M * 3, ErrorCode.PARAMS_ERROR, "图片大小不能超过3M");
        // 校验后缀
        // 获取文件后缀
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 校验后缀
        final List<String> fileSuffixList = Arrays.asList("png", "jpg", "jpeg", "webp");
        ThrowUtils.throwIf(!fileSuffixList.contains(suffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
    }

    //  新增的方法

    /**
     *  通过URL上传图片
     * @param fileUrl 图片URL
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
//    public PictureUploadResult uploadPictureByUrl(String fileUrl, String uploadPathPrefix) {
//        // 校验图片
////        validPicture(multipartFile);
//        //  新增根据url校验图片
//        String Suffix = validPicture(fileUrl);
//        // 图片地址
//        //  根据url后缀获取名称
////        String Suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
//        String fileName = FileUtil.mainName(fileUrl);
//
//        String uploadFilename = String.format("%s_%s.%s", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
//                RandomUtil.randomString(8), Suffix);
//        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
//
//        // 文件目录
//        String filename = fileName + "." + Suffix;
//        String filepath = String.format("/test/%s", filename);
//        File file = null;
//        try {
//            // 上传文件
//            file = File.createTempFile(filepath, null);
////            multipartFile.transferTo(file);
//            // 从url中下载图片
//            HttpUtil.downloadFileFromUrl(fileUrl, file);
//            PutObjectResult putObjectResult = cosManager.putPictureObject(file, uploadPath);
//            // 获取图片信息
//            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
//            int PictureHeight = imageInfo.getHeight();
//            int PictureWidth = imageInfo.getWidth();
//
//            // 封装信息
//            PictureUploadResult pictureUploadResult = new PictureUploadResult();
//            pictureUploadResult.setName(fileName);
//            pictureUploadResult.setUrl(cosClientConfig.getHost() + uploadPath);
//            pictureUploadResult.setPicFormat(imageInfo.getFormat());
//            pictureUploadResult.setPicSize(FileUtil.size(file));
//            pictureUploadResult.setPicHeight(PictureHeight);
//            pictureUploadResult.setPicWidth(PictureWidth);
//            // 这里将整数转化为double，避免精度丢失
//            pictureUploadResult.setPicScale(PictureHeight * 1.0 / PictureWidth);
//            return pictureUploadResult;
//        } catch (Exception e) {
//            log.error("文件上传失败: {}", filepath, e);
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
//        } finally {
//            deleteTempFile(file, filepath);
//        }
//
//    }

    /**
     * 根据校验图片
     *
     * @param fileUrl 图片url
     */
    private String validPicture(String fileUrl) {
        return null;
    }
}
